// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common

GraphicsBox {
  id: root

  // property var refreshitems: []
  property var seats: []
  property var select_cards: []
  property var selected_cards: []
  property var retselected_cards: []
  property var all_selavamap: [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]

  property string my_selectgenname:""
  property string my_selectedgenname:""

  property int repcount: 0
  property int seat: -1
  property int my_selectedseat: 0
  property int realnum: 0

  property bool selbtn_visible:false

  property var textRefs:[]
  property var selectedcardRefs:[]

  width: 620
  height: gens_selected.height + title.height + gridlay.height + 45

  Item {
    id: gens_selected
    width: 600
    height: selectedFlick.height
    anchors.top: title.bottom
    anchors.topMargin:10
    anchors.left: root.left
    anchors.leftMargin: seats.length < 4 ? 120 : 55

    Flickable {
      id:selectedFlick
      flickableDirection: Flickable.HorizontalFlick
      // anchors.horizontalCenter: root.horizontalCenter
      // anchors.top: myseltitle.bottom
      // anchors.topMargin: 3
      width: seats.length < 4 ? 400 : (560+(seats.length-4)*150)
      height: selectedLayout.height
      contentWidth: seats.length < 4 ? 400 : (560+(seats.length-4)*150)
      clip: true

      RowLayout {
        id : selectedLayout
        spacing: seats.length < 4 ? 60 : 40
        Repeater {
          id:selectedRepeater
          model: selected_cards
          delegate: Item  {
            // scale:0.8
            width:gencard.width
            height:200

            property var selectedcard:null

            MetroButton {
              id: selected_btn
              visible:index === my_selectedseat && modelData !== "请选将"
              anchors.top: gencard.bottom
              anchors.left: gencard.left
              anchors.leftMargin:26
              text: "确定"
              width: 55
              height: 32

              onClicked: {     
                if(modelData === root.my_selectgenname && root.my_selectedgenname === ""){
                  root.my_selectedgenname = modelData
                  text = "取消"
                  root.retselected_cards[index] = modelData    
                  gencard.chosenInBox = true
                  if(realnum == 1){
                    ClientInstance.replyToServer("", modelData);
                    close();         
                    roomScene.state = "notactive";
                  }else{
                    refSelected(modelData)
                  }
                }else{
                  text = "确定"
                  root.my_selectedgenname = ""
                  root.retselected_cards[index] = "请选将"
                  gencard.chosenInBox = false
                  ClientInstance.notifyServer("PushRequest", "updatemini,selected," + seat + "," + "cancel");
                }
              }
            }

            Text {
              id: selfname
              visible:true
              anchors.top: parent.top
              anchors.left: parent.left
              anchors.leftMargin:5
              text:{
                if(index === my_selectedseat){
                  return "自己" + "("+root.seats[index] + "号位" +")"
                }else{
                  return root.seats[index] + "号位"
                }
              }
              color: {
                if(index === my_selectedseat){
                  return "red"
                }else{
                  return "#90EE90"
                }
              }
              // "#90EE90"
              font.family: Config.libianName
              font.bold: true
              font.pixelSize: 16
              style: Text.Outline
              wrapMode: Text.WordWrap
              // verticalAlignment: Text.AlignVCenter
              // horizontalAlignment: Text.AlignHCenter
            }

            GeneralCardItem{
              id:gencard
              name: modelData
              selectable: true
              anchors.top: selfname.bottom
              chosenInBox: root.retselected_cards[index] !== "请选将"
              onRightClicked: {
                roomScene.startCheat("GeneralDetail", { generals: [modelData] });
              }
            }    
            Component.onCompleted: {
            // 将组件引用存入全局数组
              // console.log(index)
              selectedcard = gencard
              // console.log(selected_btn.visible)
              root.selectedcardRefs[index] = selectedcard;
            }
            Component.onDestruction: {
              root.selectedcardRefs[index] = undefined;
            }
          }
        }
      }
    }
  }

  Item{
    id:griditem
    width: 600
    height: 150
    anchors.top: gens_selected.bottom
    anchors.topMargin:2
    anchors.left: root.left
    anchors.leftMargin:25

    GridLayout {
      id: gridlay
      clip: true
      width: parent.width
      height: parent.height

      anchors.top: parent.top
      // anchors.topMargin:5
      rowSpacing: 0
      columnSpacing: 6
      columns: 8

      Repeater {
        id: listrep

        model: select_cards
        delegate: Item {
          // id:genpicitem
          width: 50
          height: 60

          property var avainnerText:null
          
          Item {
            id:avalistitem
            width: parent.width
            height: parent.height
            anchors.top: parent.top
            anchors.topMargin:10
            Text {
              id: avaitemtxt
              visible: true
              anchors.bottom: generalPic.top
              // anchors.horizontalCenter: gencard.horizontalCenter
              text: ""
              color: "#90EE90"
              font.family: Config.libianName
              font.bold: true
              font.pixelSize: 15
              style: Text.Outline
              wrapMode: Text.WordWrap
              // verticalAlignment: Text.AlignVCenter
              // horizontalAlignment: Text.AlignHCenter
            }

            Avatar {
              id: generalPic
              width: 50; height: 50
              anchors.top: avaitemtxt.bottom
              // anchors.left: parent.left
              // anchors.margins: 8
              general: modelData
              TapHandler {
                onTapped: {                  
                  if(root.my_selectedgenname === ""&& avaitemtxt.text === ""){
                    if(root.all_selavamap[seat-1] > -1){
                      root.textRefs[root.all_selavamap[seat-1]].text = ""
                    }
                    avaitemtxt.text = "我"
                    let genname = root.select_cards[index]
                    refreshGenCards(genname,index)
                  }                 
                }
              }
            }
          }
          Component.onCompleted: {
            avainnerText = avaitemtxt
            root.textRefs[index] = avainnerText;
          }
          Component.onDestruction: {
            root.textRefs[index] = undefined;
          }
        }
      }
    }
  }

  function refreshGenCards(name,pos) {
    all_selavamap[seat-1] = pos

    my_selectgenname = name
    selected_cards[my_selectedseat] = name
    selectedRepeater.model = selected_cards
    // selected_cards.setProperty(my_selectedseat, "propertyName", name)
    ClientInstance.notifyServer("PushRequest", "updatemini,preselect," + seat + "," + pos); 
  }

  function updateData(data) {
    let [type, value,newvalue] = data;
    value = value ?? "";
    // console.log("===更新"+ value +"号玩家数据===")
    // console.log(value)
    // console.log(newvalue)
    
    if (type == "preselect") {
      let refreshseat = parseInt(value)
      let refresh_avapicpos = parseInt(newvalue)
      if(textRefs[refresh_avapicpos].text !== "") {return}
      if(all_selavamap[refreshseat-1] > -1){
        textRefs[all_selavamap[refreshseat-1]].text = ""
      }
      all_selavamap[refreshseat-1] = refresh_avapicpos
      // root.textRefs.forEach(txt=>{
      //   // console.log(txt)
      //   if(txt.visible && txt.text !== "我"){
      //     txt.visible = false
      //   }
      // })
      textRefs[refresh_avapicpos].text = refreshseat + "号位"

      let other_selectedseat = seats.indexOf(refreshseat)
      let other_selectgenname = select_cards[refresh_avapicpos]
      selected_cards[other_selectedseat] = other_selectgenname
      selectedcardRefs[other_selectedseat].name = other_selectgenname
    } else if (type == "selected") {
      let refreshseat = parseInt(value)
      let isok = newvalue === "ok" ? true : false
      let other_selectedseat = seats.indexOf(refreshseat)
      selectedcardRefs[other_selectedseat].chosenInBox = isok
      if(isok){
        let selname = selectedcardRefs[other_selectedseat].name
        retselected_cards[other_selectedseat] = selname
        let realselectednum = 0
        retselected_cards.forEach(g=>{
          // console.log(g)
          if(g !== "请选将"){
            realselectednum++
          }
        })
        // console.log("是否被可以关闭选将界面")
        // console.log(realselectednum)
        // console.log(realnum)
        if(realselectednum >= realnum){//关闭其他人选将界面并返回选将数据
          ClientInstance.replyToServer("", retselected_cards[my_selectedseat]);
          close();
          roomScene.state = "notactive";
        }
      }else{
        retselected_cards[other_selectedseat] = "请选将"
      }
    } else if (type == "updataRepGen") {
      
    } else if (type == "updateFriendCards") {
      
    }
  }

  Timer {
    id: delayRefTimer
    interval: 10  // 设置延时时间，单位为毫秒
    onTriggered: {
      // 这里是延时后要执行的代码
      let refcards = selected_cards
      selectedRepeater.model = []
      selectedRepeater.model = refcards
    }
  }

  function refSelected(data) {
    let realselectednum = 0
    retselected_cards.forEach(g=>{
      // console.log(g)
      if(g !== "请选将"){
        realselectednum++
      }
    })
    // console.log("我已选完将。通知其他人。")
    // console.log(realselectednum)   
    // console.log(realnum) 
    ClientInstance.notifyServer("PushRequest", "updatemini,selected," + seat + "," + "ok");               
    if(realselectednum >= realnum){
      // delayRetSelectedTimer.start()
      ClientInstance.replyToServer("", data);
      close();
      roomScene.state = "notactive";
    } 
  }

  // Timer {
  //   id: delayRetSelectedTimer
  //   interval: 2000  // 设置延时时间，单位为毫秒
  //   onTriggered: {
  //     console.log("自己关闭选将界面（所有人已选将）")
  //     let realselectednum = 0
  //     retselected_cards.forEach(g=>{
  //       // console.log(g)
  //       if(g !== "请选将"){
  //         realselectednum++
  //       }
  //     })
  //     console.log(realselectednum)                 
  //     if(realselectednum >= realnum){
  //       // root.close();
  //       // roomScene.state = "notactive";
  //     }
  //   }
  // }
  

  function loadData(data) {
    root.title.text = "选将"
    select_cards = data.gens;
    seat = data.seat
    seats = data.seats;
    realnum = data.realnum;
    selected_cards = data.selected_cards;
    for(let i = 0;i < selected_cards.length;i++){
      retselected_cards.push(selected_cards[i])
    }
    // console.log(realnum)
    // console.log(selected_cards)
    delayRefTimer.start()
    // let playerinfo = leval(
    //   `(function()
    //     local player = ClientInstance:getPlayerById(${Self.id})
    //     return {
    //       id = player.id,
    //       general = player.general,
    //       deputyGeneral = player.deputyGeneral,
    //       screenName = player.player:getScreenName(),
    //       kingdom = player.kingdom,
    //       seat = player.seat,
    //       role = player.role,
    //     }
    //   end)()`
    // );
    // console.log(playerinfo)
    // console.log(playerinfo.seat)
    my_selectedseat = seats.indexOf(data.seat)
    // console.log(Self.seat)
  }
}
